package com.umeox.recorder

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.umeox.moto.common.utils.FileUtils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.util.UToast
import com.umeox.recorder.Recorder.OnRecorderListener
import com.umeox.recorder.data.RecorderBean
import com.umeox.recorder.data.RecorderDataBase
import com.umeox.recorder.databinding.ActivityRecordAddBinding
import java.io.File
import java.io.IOException
import java.util.Locale
import java.util.concurrent.TimeUnit


class RecordAddActivity : ThemeAppCompatActivity() {
    private lateinit var mBinding: ActivityRecordAddBinding
    private lateinit var mRecorder: Recorder

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mRecorder = Recorder.getInstance()
        mRecorder.setOnRecorderListener(RecordListener())

        mBinding = ActivityRecordAddBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        val snapHelper = LinearSnapHelper()
        snapHelper.attachToRecyclerView(mBinding.rvAnim)
        mBinding.rvAnim.adapter = object : Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                return object : ViewHolder(layoutInflater.inflate(R.layout.item_record_anim, parent, false)) {}
            }

            override fun getItemCount(): Int {
                return Int.MAX_VALUE
            }

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {}
        }

        //屏蔽对动画控件的点击
        mBinding.viewBlock.setOnTouchListener { _, _ ->
            return@setOnTouchListener true
        }

        mBinding.btnMain.setOnClickListener {
            if (!mIsRecording) {
                saveFlag = false
                startRecord()
            } else {
                //只有点击停止按钮才保存文件
                saveFlag = true
                stopRecord()
                finish()
            }
        }

        mBinding.tvTime.text = getTimeStr(0)
    }

    private var mIsRecording = false
    private var saveFlag = false

    private fun startRecord() {
        mBinding.btnMain.background = ResourcesCompat.getDrawable(resources, R.drawable.recorder_icon_stop, null)
        val rv = mBinding.rvAnim
        val scroller = object : RecyclerView.SmoothScroller() {
            override fun onStart() {
                rv.scrollBy(-rv.scrollX, 0)
            }

            override fun onStop() {
            }

            override fun onSeekTargetStep(dx: Int, dy: Int, state: RecyclerView.State, action: Action) {
                action.dx = rv.width
                action.duration = 5000
            }

            override fun onTargetFound(targetView: View, state: RecyclerView.State, action: Action) {
                action.dx = rv.width
                action.duration = 5000
            }
        }
        val lm = rv.layoutManager as LinearLayoutManager
        scroller.targetPosition = rv.adapter?.itemCount ?: (Int.MAX_VALUE - 1)
        lm.startSmoothScroll(scroller)
        rv.visibility = View.VISIBLE
        mRecorder.start()
        mIsRecording = true
        window.addFlags(FLAG_KEEP_SCREEN_ON)
    }

    private fun stopRecord() {
        if (!mIsRecording) return
        mBinding.btnMain.background = ResourcesCompat.getDrawable(resources, R.drawable.recorder_icon_start, null)
        val rv = mBinding.rvAnim
        rv.stopScroll()
        rv.visibility = View.INVISIBLE
        mRecorder.stop()
        mIsRecording = false
        mBinding.btnMain.isClickable = false
        window.clearFlags(FLAG_KEEP_SCREEN_ON)
    }

    private fun getTimeStr(time: Long): String {
        val ms = time % 1000
        val s = time / 1000 % 60
        val m = time / 1000 / 60
        return String.format(Locale.getDefault(), "%02d:%02d:%02d", m, s, ms / 10)
    }

    private inner class RecordListener : OnRecorderListener {
        override fun onComplete(filePath: String, startMillis: Long, duration: Long) {
            if (!saveFlag || duration < TimeUnit.SECONDS.toMillis(1)) return
            val recorderBean = RecorderBean()
            recorderBean.createTime = startMillis
            recorderBean.filePath = filePath
            recorderBean.duration = duration
            recorderBean.name = File(filePath).nameWithoutExtension
            RecorderDataBase.getInstance(this@RecordAddActivity)
                .recorderDao
                .save(recorderBean)
                .subscribe()
            stopRecord()
            finish()
        }

        override fun onUpdate(duration: Long) {
            mBinding.tvTime.text = getTimeStr(duration)
        }

        override fun onError(e: IOException) {
            if (10 * 1024 * 1024 > FileUtils.getAvailableInternalMemory()) {
                UToast.showCustomToast(mContext, R.string.low_memory, Toast.LENGTH_LONG)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopRecord()
    }
}
